package com.onlineMIS.ORM.DAO.headQ.barCodeGentor;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.components.UIBean;
import org.apache.struts2.views.jsp.ui.HeadTag;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.mapping.Array;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang.StringUtils;

import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.chainS.user.ChainRoleTypeDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.SQLServer.ColorMSDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.SQLServer.SizeMSDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.finance.ExpenseHqTypeImpl;
import com.onlineMIS.ORM.DAO.headQ.inventoryFlow.HeadQInventoryStoreDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.systemConfig.SystemConfigDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.systemFile.SystemFileDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.user.SystemRoleMenuDaoImpl;
import com.onlineMIS.ORM.entity.base.BaseOrder;
import com.onlineMIS.ORM.entity.chainS.user.ChainRoleType;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Brand;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.BrandVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Category;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Color;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ExpenseTypeVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadQTag;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadQTagGroup;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadQTagGroupVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadQTagVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Menu;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.MenuVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.NumPerHand;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Product;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductDTO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductIdentitySequence;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ProductUnit;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Quarter;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Size;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.SystemConfig;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.SystemConfigVO;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.SystemFile;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Year;
import com.onlineMIS.ORM.entity.headQ.custMgmt.HeadQCust;
import com.onlineMIS.ORM.entity.headQ.custMgmt.HeadQCustVO;
import com.onlineMIS.ORM.entity.headQ.finance.ExpenseHqType;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadQInventoryStore;
import com.onlineMIS.ORM.entity.headQ.user.SystemRoleMenu;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.action.headQ.barCodeGentor.BasicDataActionFormBean;
import com.onlineMIS.action.headQ.barCodeGentor.BasicDataActionUIBean;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.DateUtils;
import com.onlineMIS.common.StrCheckUtils;
import com.onlineMIS.common.loggerLocal;
import com.onlineMIS.filter.SystemParm;

@Service
public class BasicDataService {
	@Autowired
    private BrandDaoImpl brandDaoImpl;
	@Autowired
    private CategoryDaoImpl categoryDaoImpl;
	@Autowired
	private ColorDaoImpl colorDaoImpl;
	@Autowired
	private MenuService menuService;
	@Autowired
	private SizeDaoImpl sizeDaoImpl;
	@Autowired
	private YearDaoImpl yearDaoImpl;
	@Autowired
	private QuarterDaoImpl quarterDaoImpl;
	@Autowired
	private ProductUnitDaoImpl productUnitDaoImpl;
	@Autowired
	private NumPerHandDaoImpl numPerHandDaoImpl;
	@Autowired
	private ColorMSDAOImpl colorMSDAOImpl;
	@Autowired
	private SizeMSDAOImpl sizeMSDAOImpl;
	@Autowired
	private HeadQInventoryStoreDAOImpl inventoryStoreDAOImpl;
	@Autowired
	private ChainRoleTypeDaoImpl chainRoleTypeDaoImpl;
	@Autowired
	private HeadQTagDaoImpl headQTagDaoImpl;
	@Autowired
	private HeadQTagGroupDaoImpl headQTagGroupDaoImpl;
	@Autowired
	private ExpenseHqTypeImpl expenseHqTypeImpl;
	@Autowired
	private SystemConfigDaoImpl systemConfigDaoImpl;
	@Autowired
	private SystemFileDaoImpl systemFileDaoImpl;
	@Autowired
	private ProductDaoImpl productDaoImpl;
	@Autowired
	private ProductBarcodeService productBarcodeService;
	@Autowired
	private ProductIdentitySequenceDaoImpl productIsDaoImpl;
	@Autowired
	private SystemRoleMenuDaoImpl systemRoleMenuDaoImpl;

	

	/**
	 * get the brand information by id
	 * @param id
	 * @return
	 */
	public Brand getBrand(int id){
		Brand brand = brandDaoImpl.get(id,true);

		return brand;
	}
	
	/**
	 * save or update brand inforamtion
	 * @param brand
	 */
	public void saveOrUpdateBrand(Brand brand) {
		this.brandDaoImpl.saveOrUpdate(brand,true);
		
	}
	
	/**
	 * save or update category inforamtion
	 * @param category
	 */
	public void saveOrUpdateCategory(Category category) {
		this.categoryDaoImpl.saveOrUpdate(category,true);
		
	}

	/**
	 * get category information by id
	 * @param id
	 * @return
	 */
	public Category getCategory(int id) {
		Category category = categoryDaoImpl.get(id,true);
		return category;
	}




	/**
	 * 准备List UI数据
	 * @param uiBean
	 * @param basicData
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public Response prepareListUI(String basicData, Integer page, Integer rowPerPage, String sort, String sortOrder, Brand brand, Category category) throws IllegalAccessException, InvocationTargetException {
		Response response = new Response();
		Map dataMap = new HashMap();

		if (basicData.equalsIgnoreCase("quarter")){
			//1. 获取总条数
			DetachedCriteria quarterTotalCriteria = DetachedCriteria.forClass(Quarter.class);
			quarterTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(quarterDaoImpl.getByCriteriaProjection(quarterTotalCriteria, true));
			
			//2. 获取当页数据
			DetachedCriteria quarterCriteria = DetachedCriteria.forClass(Quarter.class);
			List<Quarter> brands = quarterDaoImpl.getByCritera(quarterCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			
			dataMap.put("rows", brands);
			dataMap.put("total", total);
		} else if (basicData.equalsIgnoreCase("brand")){
			//1. 获取总条数
			DetachedCriteria brandTotalCriteria = DetachedCriteria.forClass(Brand.class);
			if (brand != null) {
				String brandName = brand.getBrand_Name().trim();
				String supplier = brand.getSupplier().trim();
				String comment = brand.getComment().trim();
				
				if (!brandName.isEmpty())
					brandTotalCriteria.add(Restrictions.ilike("pinyin", "%"+brandName+"%"));
				if (!supplier.isEmpty())
					brandTotalCriteria.add(Restrictions.ilike("supplier", "%"+supplier+"%"));
				if (!comment.isEmpty())
					brandTotalCriteria.add(Restrictions.like("comment", "%"+comment+"%"));
			}
			brandTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(brandDaoImpl.getByCriteriaProjection(brandTotalCriteria, true));
			
			//2. 获取当页数据
			DetachedCriteria brandCriteria = DetachedCriteria.forClass(Brand.class);
			if (brand != null) {
				String brandName = brand.getBrand_Name().trim();
				String supplier = brand.getSupplier().trim();
				String comment = brand.getComment().trim();
				
				if (!brandName.isEmpty())
					brandCriteria.add(Restrictions.ilike("brand_Name", "%"+brandName+"%"));
				if (!supplier.isEmpty())
					brandCriteria.add(Restrictions.ilike("supplier", "%"+supplier+"%"));
				if (!comment.isEmpty())
					brandCriteria.add(Restrictions.like("comment", "%"+comment+"%"));
			}
			if (sortOrder.equalsIgnoreCase("desc"))
				brandCriteria.addOrder(Order.desc(sort));
			else 
				brandCriteria.addOrder(Order.asc(sort));
			List<Brand> bs = brandDaoImpl.getByCritera(brandCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			List<BrandVO> brands = new ArrayList<BrandVO>();
			for (Brand brand2 : bs) {
				BrandVO brandVO = new BrandVO(brand2);
				brands.add(brandVO);
			}
			
			dataMap.put("rows", brands);
			dataMap.put("total", total);
		} else if (basicData.equalsIgnoreCase("category")){
			//1. 获取总条数
			DetachedCriteria categoryTotalCriteria = DetachedCriteria.forClass(Category.class);
			//2. 获取当页数据
			DetachedCriteria categoryCriteria = DetachedCriteria.forClass(Category.class);
			
			if (category != null) {
                			
				if (!StringUtils.isEmpty(category.getCategory_Name())) {
					String categoryName = category.getCategory_Name().trim();
					categoryTotalCriteria.add(Restrictions.like("category_Name", "%"+categoryName+"%"));
					categoryCriteria.add(Restrictions.like("category_Name", "%"+categoryName+"%"));
				}
				
				if (category.getStatus() != Common_util.ALL_RECORD) {
					categoryTotalCriteria.add(Restrictions.eq("status", category.getStatus()));
					categoryCriteria.add(Restrictions.eq("status", category.getStatus()));
				}
				
				
				categoryTotalCriteria.add(Restrictions.eq("level", Category.LEVEL2));
				categoryCriteria.add(Restrictions.eq("level", Category.LEVEL2));
				
					
			}
			categoryTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(categoryDaoImpl.getByCriteriaProjection(categoryTotalCriteria, true));

			categoryCriteria.addOrder(Order.desc("level"));
			
			List<Category> categories = categoryDaoImpl.getByCritera(categoryCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			
			dataMap.put("rows", categories);
			dataMap.put("total", total);
		}else if (basicData.equalsIgnoreCase("categoryLevel")){
			//1. 获取总条数
			DetachedCriteria categoryTotalCriteria = DetachedCriteria.forClass(Category.class);
			//2. 获取当页数据
			DetachedCriteria categoryCriteria = DetachedCriteria.forClass(Category.class);
			
			if (category != null) {
                			
				if (!StringUtils.isEmpty(category.getCategory_Name())) {
					String categoryName = category.getCategory_Name().trim();
					categoryTotalCriteria.add(Restrictions.like("category_Name", "%"+categoryName+"%"));
					categoryCriteria.add(Restrictions.like("category_Name", "%"+categoryName+"%"));
				}
				
				if (category.getStatus() != Common_util.ALL_RECORD) {
					categoryTotalCriteria.add(Restrictions.eq("status", category.getStatus()));
					categoryCriteria.add(Restrictions.eq("status", category.getStatus()));
				}							
					categoryTotalCriteria.add(Restrictions.eq("level", Category.LEVEL1));
					categoryCriteria.add(Restrictions.eq("level", Category.LEVEL1));
				
					
			}
			categoryTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(categoryDaoImpl.getByCriteriaProjection(categoryTotalCriteria, true));

			categoryCriteria.addOrder(Order.desc("level"));
			
			List<Category> categories = categoryDaoImpl.getByCritera(categoryCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			
			dataMap.put("rows", categories);
			dataMap.put("total", total);
		} else if (basicData.equalsIgnoreCase("color")){ 
			//1. 获取总条数
			DetachedCriteria colorTotalCriteria = DetachedCriteria.forClass(Color.class);
			colorTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(colorDaoImpl.getByCriteriaProjection(colorTotalCriteria, true));
			
			//2. 获取当页数据
			DetachedCriteria colorCriteria = DetachedCriteria.forClass(Color.class);
			if (sortOrder.equalsIgnoreCase("desc"))
				colorCriteria.addOrder(Order.desc(sort));
			else 
				colorCriteria.addOrder(Order.asc(sort));
			List<Color> colors = colorDaoImpl.getByCritera(colorCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			
			dataMap.put("rows", colors);
			dataMap.put("total", total);
		} else if (basicData.equalsIgnoreCase("productUnit")){ 
			//1. 获取总条数
			DetachedCriteria productUnitTotalCriteria = DetachedCriteria.forClass(ProductUnit.class);
			productUnitTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(productUnitDaoImpl.getByCriteriaProjection(productUnitTotalCriteria, true));
			
			//2. 获取当页数据
			DetachedCriteria productUnitCriteria = DetachedCriteria.forClass(ProductUnit.class);
			List<ProductUnit> productUnits = productUnitDaoImpl.getByCritera(productUnitCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			
			dataMap.put("rows", productUnits);
			dataMap.put("total", total);
		} else if (basicData.equalsIgnoreCase("numPerHand")){ 
			//1. 获取总条数
			DetachedCriteria numPerHandTotalCriteria = DetachedCriteria.forClass(NumPerHand.class);
			numPerHandTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(numPerHandDaoImpl.getByCriteriaProjection(numPerHandTotalCriteria, true));
			
			//2. 获取当页数据
			DetachedCriteria numPerHandCriteria = DetachedCriteria.forClass(NumPerHand.class);
			List<NumPerHand> numPerHands = numPerHandDaoImpl.getByCritera(numPerHandCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			
			dataMap.put("rows", numPerHands);
			dataMap.put("total", total);
		} else if (basicData.equalsIgnoreCase("inventory")){  //总部仓库
			
			//2. 获取当页数据
			List<HeadQInventoryStore> numPerHands = inventoryStoreDAOImpl.getAll(true);
			if (numPerHands.size() !=0) {
				for (HeadQInventoryStore headQInventoryStore : numPerHands) {
					headQInventoryStore.init();
				}
			}
			
			dataMap.put("rows", numPerHands);
			dataMap.put("total", 0);
		}else if (basicData.equalsIgnoreCase("tag")){  //总部标签
			
			//1. 获取总条数
			//DetachedCriteria tagTotalCriteria = DetachedCriteria.forClass(HeadQTag.class);
			//tagTotalCriteria.setProjection(Projections.rowCount());
			//int total = Common_util.getProjectionSingleValue(numPerHandDaoImpl.getByCriteriaProjection(tagTotalCriteria, true));
			
			//2. 获取当页数据
			DetachedCriteria tagCriteria = DetachedCriteria.forClass(HeadQTag.class);
			tagCriteria.addOrder(Order.asc("groupId"));
			List<HeadQTag> tags = headQTagDaoImpl.getByCritera(tagCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			
			List<HeadQTagVO> tagVOs = new ArrayList<HeadQTagVO>();
			for (HeadQTag headQTag : tags) {
				HeadQTagVO vo = new HeadQTagVO(headQTag);
				tagVOs.add(vo);
			}

			dataMap.put("rows", tagVOs);
			//dataMap.put("total", total);		
		}else if (basicData.equalsIgnoreCase("tagGroup")){  //总部标签
			List<HeadQTagGroupVO> list = new ArrayList<HeadQTagGroupVO>();
			//1. 获取总条数
//			DetachedCriteria tagTotalCriteria = DetachedCriteria.forClass(HeadQTagGroup.class);
//			tagTotalCriteria.setProjection(Projections.rowCount());
//			int total = Common_util.getProjectionSingleValue(numPerHandDaoImpl.getByCriteriaProjection(tagTotalCriteria, true));
//			
			//2. 获取当页数据
			DetachedCriteria tagCriteria = DetachedCriteria.forClass(HeadQTagGroup.class);
			tagCriteria.addOrder(Order.asc("sort"));
			List<HeadQTagGroup> tagGroups = headQTagGroupDaoImpl.getByCritera(tagCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			if (tagGroups.size() !=0) {
				for (HeadQTagGroup headQTagGroup : tagGroups) {
					HeadQTagGroupVO vo = new HeadQTagGroupVO();
					vo.setId(headQTagGroup.getId());
					vo.setGroupName(headQTagGroup.getGroupName());
					vo.setEntityType(HeadQTagGroup.map.get(headQTagGroup.getEntityType()));
					vo.setSort(headQTagGroup.getSort());
					list.add(vo);
				}
			}
			dataMap.put("rows", list);
//			dataMap.put("total", total);		
		}else if (basicData.equalsIgnoreCase("ExpenseHqType")){  //费用类型
			List<ExpenseTypeVO> list = new ArrayList<ExpenseTypeVO>();
			//1. 获取总条数
			DetachedCriteria tagTotalCriteria = DetachedCriteria.forClass(ExpenseHqType.class);
			tagTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(expenseHqTypeImpl.getByCriteriaProjection(tagTotalCriteria, true));
//			
			//2. 获取当页数据
			DetachedCriteria tagCriteria = DetachedCriteria.forClass(ExpenseHqType.class);
			tagCriteria.addOrder(Order.asc("sort"));
			List<ExpenseHqType> types = expenseHqTypeImpl.getByCritera(tagCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			if (types.size() !=0) {
				for (ExpenseHqType expenseHqType : types) {
					ExpenseTypeVO vo = new ExpenseTypeVO();
					vo.setId(expenseHqType.getId());
					vo.setExpenseName(expenseHqType.getName());
					if (expenseHqType.getBelong() == ExpenseHqType.BELONG_TO_CHAIN) {
						vo.setBelongToS("店铺");
					}else {
						vo.setBelongToS("总部");					
					}					
					
					if (expenseHqType.getStatus() == 0) {
						vo.setStatusS("正常");
						
					}else {
						vo.setStatusS("停用");
					}
					vo.setStatus(expenseHqType.getStatus());
					//上级费用名称
					if (expenseHqType.getParentId() != null)  {
						ExpenseHqType expen = expenseHqTypeImpl.get(expenseHqType.getParentId(), true);
						if (expen != null) {
							vo.setParentName(expen.getName());
						}												
					}else {
						if (expenseHqType.getBelong() == ExpenseHqType.BELONG_TO_CHAIN) {
							vo.setParentName("店铺费用");
						}else {
							vo.setParentName("总部费用");
						}
					}			
					vo.setSort(expenseHqType.getSort());
					vo.setComment(expenseHqType.getComment());
					if (expenseHqType.getCreateBy() == null) {
						vo.setCreateBy("admin");
					}
					vo.setCreateBy(expenseHqType.getCreateBy());
					if (expenseHqType.getCreateTime() != null) {
						vo.setCreateTime(Common_util.dateFormat_f.format(expenseHqType.getCreateTime()));
					}					
					if (expenseHqType.getUpdateBy() == null) {
						vo.setUpdateBy("admin");
					}
					vo.setUpdateBy(expenseHqType.getUpdateBy());
					if (expenseHqType.getUpdateTime() != null) {
						vo.setUpdateTime(Common_util.dateFormat_f.format(expenseHqType.getUpdateTime()));	
					}		
					list.add(vo);
				}

			}
			dataMap.put("rows", list);
			dataMap.put("total", total);	
			
		}else {
			//1. 获取总条数
			DetachedCriteria yearTotalCriteria = DetachedCriteria.forClass(Year.class);
			yearTotalCriteria.setProjection(Projections.rowCount());
			int total = Common_util.getProjectionSingleValue(yearDaoImpl.getByCriteriaProjection(yearTotalCriteria, true));
			
			//2. 获取当页数据
			DetachedCriteria yearCriteria = DetachedCriteria.forClass(Year.class);
			List<Year> years = yearDaoImpl.getByCritera(yearCriteria, Common_util.getFirstRecord(page, rowPerPage), rowPerPage, true);
			
			dataMap.put("rows", years);
			dataMap.put("total", total);
		}
		
		response.setReturnValue(dataMap);
		response.setReturnCode(Response.SUCCESS);
		return response;
	}

	public Object getBasicData(String basicData, Integer basicDataId) {
		if (basicDataId != null)
			if (basicData.equalsIgnoreCase("quarter")){
				Quarter quarter = quarterDaoImpl.get(basicDataId, true);
				return quarter;
			} else if (basicData.equalsIgnoreCase("brand")){
				Brand brand = brandDaoImpl.get(basicDataId, true);
				return brand;	
			} else if (basicData.equalsIgnoreCase("category")){
				Category category = categoryDaoImpl.get(basicDataId, true);
				return category;
			} else if (basicData.equalsIgnoreCase("categoryLevel")){
				Category category = categoryDaoImpl.get(basicDataId, true);
				return category;
			}else if (basicData.equalsIgnoreCase("color")){ 
				Color color = colorDaoImpl.get(basicDataId, true);
				return color;
			} else if (basicData.equalsIgnoreCase("year")){ 
				Year year = yearDaoImpl.get(basicDataId, true);
				return year;
			} else if (basicData.equalsIgnoreCase("numPerHand")){
                NumPerHand numPerHand = numPerHandDaoImpl.get(basicDataId, true);
				return numPerHand;	
			} else if (basicData.equalsIgnoreCase("productUnit")){ 
				ProductUnit productUnit = productUnitDaoImpl.get(basicDataId, true);
				return productUnit;
			}else if (basicData.equalsIgnoreCase("inventory")){ 
				HeadQInventoryStore store = inventoryStoreDAOImpl.get(basicDataId, true);
				return store;
			}else if (basicData.equalsIgnoreCase("role")){ 
				ChainRoleType role = chainRoleTypeDaoImpl.get(basicDataId, true);
				return role;
			}else if (basicData.equalsIgnoreCase("tag")){ 
				HeadQTag tag = headQTagDaoImpl.get(basicDataId, true);
				return tag;
			}else if (basicData.equalsIgnoreCase("tagGroup")){ 
				HeadQTagGroup tagGroup = headQTagGroupDaoImpl.get(basicDataId, true);
				return tagGroup;
			}else if (basicData.equalsIgnoreCase("expenseType")){ 
				ExpenseHqType ExpenseHqType = expenseHqTypeImpl.get(basicDataId, true);
				List<ExpenseHqType> list = expenseHqTypeImpl.selectTypes();

				ExpenseHqType.setList(list);

				return ExpenseHqType;
			}
			
		return null;
	}

	@Transactional
	public Response updateYear(Year year) {
		Response response = new Response();
		
		int yearId = year.getYear_ID();
		String yearS = year.getYear();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Year.class);
		criteria.add(Restrictions.eq("year", yearS));
		List<Year> years = yearDaoImpl.getByCritera(criteria, true);
		
		if (years == null || years.size() == 0){
			year.setYear_Code(yearS.substring(3));
			yearDaoImpl.saveOrUpdate(year, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			Year year2 = years.get(0);
			if (yearId != year2.getYear_ID()){
				response.setQuickValue(Response.FAIL, "年份 重复,请检查重新输入");
			} else {
				year.setYear_Code(yearS.substring(3));
				yearDaoImpl.saveOrUpdate(year, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}

	@Transactional
	public Response updateQuarter(Quarter quarter) {
		Response response = new Response();
		
		int quarterId = quarter.getQuarter_ID();
		String quarterS = quarter.getQuarter_Name();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Quarter.class);
		criteria.add(Restrictions.eq("quarter_Name", quarterS));
		List<Quarter> quarters = quarterDaoImpl.getByCritera(criteria, true);
		
		if (quarters == null || quarters.size() == 0){
			quarter.setQuarter_Code(String.valueOf(quarterId).substring(0,1));
			quarterDaoImpl.saveOrUpdate(quarter, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			Quarter quarter2 = quarters.get(0);
			if (quarterId != quarter2.getQuarter_ID()){
				response.setQuickValue(Response.FAIL, "季度 重复,请检查重新输入");
			} else {
				quarter.setQuarter_Code(String.valueOf(quarterId).substring(0,1));
				quarterDaoImpl.saveOrUpdate(quarter, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}

	@Transactional
	public synchronized Response updateBrand(Brand brand) {
Response response = new Response();
		
		try {
			int brandId = brand.getBrand_ID();		
			String brandName = brand.getBrand_Name();
			
			DetachedCriteria criteria = DetachedCriteria.forClass(Brand.class);
			criteria.add(Restrictions.eq("brand_Name", brandName));
			criteria.add(Restrictions.isNull("chainStore.chain_id"));
			
			List<Brand> brands = brandDaoImpl.getByCritera(criteria, true);

			if (brands == null || brands.size() == 0){
				brand.setBrand_Code(String.valueOf(brandId).substring(0,1));
				brand.setPinyin(Common_util.getPinyinCode(brandName, true));
				brandDaoImpl.saveOrUpdate(brand, true);
				response.setReturnCode(Response.SUCCESS);
			} else {
				Brand brand2 = brands.get(0);
				if (brandId != brand2.getBrand_ID()){
					response.setQuickValue(Response.FAIL, "品牌 重复,请检查重新输入");
				} else {
					brandDaoImpl.evict(brand2);
					brand.setBrand_Code(String.valueOf(brandId).substring(0,1));
					brand.setPinyin(Common_util.getPinyinCode(brandName, true));
					brandDaoImpl.saveOrUpdate(brand, true);
					response.setReturnCode(Response.SUCCESS);
				}
			}
		} catch (Exception e) {
			response.setFail(e.getMessage());
		}
		
		return response;
	}
	
	private int getMaxBrandNum() {
		DetachedCriteria brandCriteria = DetachedCriteria.forClass(Brand.class);
		brandCriteria.add(Restrictions.like("brand_Name", Brand.START_CHAR+"%"));
		List<Brand> brands = brandDaoImpl.getByCritera(brandCriteria, true);
		
		int maxBrandNum = 0;
		for (Brand brand : brands) {
			String brandName = brand.getBrand_Name();
			String brandNumS = brandName.replace(Brand.START_CHAR, "").trim();
			if (!brandNumS.isEmpty()) {
				int brandNum = 0;
				try {
				    brandNum = Integer.parseInt(brandNumS);
				} catch (Exception e) {
//					loggerLocal.error(e);
				}
				
				if (brandNum > maxBrandNum)
					maxBrandNum = brandNum;
			}
			brandDaoImpl.evict(brand);
		}
		
		return maxBrandNum;
	}

	@Transactional
	public Response updateCategory(Category category) {
		Response response = new Response();
		
		int categoryId = category.getCategory_ID();
		String categoryName = category.getCategory_Name();
		if (category.getCategory_Name().equals("")) {
			response.setFail("品类名称为空，请输入品类名称后再提交");
			return response;
		}
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Category.class);
		criteria.add(Restrictions.eq("category_Name", categoryName));
		List<Category> categories = categoryDaoImpl.getByCritera(criteria, true);
		
		if (categories == null || categories.size() == 0){
			String code  = categoryDaoImpl.selectMaxCode();
			category.setCategory_Code(code);
			category.setLevel(Category.LEVEL2);
			categoryDaoImpl.saveOrUpdate(category, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			Category category2 = categories.get(0);
			if (categoryId != category2.getCategory_ID()){
				response.setQuickValue(Response.FAIL, "类别 重复,请检查重新输入");
			} else {
                category2.setCategory_Name(category.getCategory_Name());
                category2.setChainId(category.getChainId());
                category2.setStatus(category.getStatus());
				categoryDaoImpl.saveOrUpdate(category2, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}
	
	
	@Transactional
	public Response updateCategoryLevel(Category category) {
		Response response = new Response();
		
		int categoryId = category.getCategory_ID();
		String categoryName = category.getCategory_Name();
		if (category.getCategory_Name().equals("")) {
			response.setFail("品类名称为空，请输入品类名称后再提交");
			return response;
		}
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Category.class);
		criteria.add(Restrictions.eq("category_Name", categoryName));
		
		List<Category> categories = categoryDaoImpl.getByCritera(criteria, true);
		
		if (categories == null || categories.size() == 0){
			category.setLevel(Category.LEVEL1);
			categoryDaoImpl.saveOrUpdate(category, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			Category ca = categories.get(0);
			if (categoryId != ca.getCategory_ID()){
				response.setQuickValue(Response.FAIL, "类别 重复,请检查重新输入");
			} else {
				ca.setCategory_Name(category.getCategory_Name());
				ca.setChainId(category.getChainId());
				ca.setCategory_Code(category.getCategory_Code());
				ca.setStatus(category.getStatus());
			
				categoryDaoImpl.saveOrUpdate(ca, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}
	
	/**
	 * 一键赋值编码
	 * @return
	 */
	@Transactional
	public Response oneKeyCategoryCode(UserInfor loginUserInfor) {
		Response response = new Response();
		//1.修改货品编码
//		List<Category> list = categoryDaoImpl.selectLecelOneCounts();
//		for (int i = 0; i < list.size(); i++) {
//				Category category = list.get(i);
//				if (!StringUtils.isEmpty(category.getCategory_Code()))
//					continue;
//				category.setCategory_Code(Common_util.formatCode(i+1, 2));
//				categoryDaoImpl.update(category, true);
//		}
//		
		//2.修改产品公司货号
		int nums = updateProductIdentity("2024", loginUserInfor);
		int numst = updateProductIdentity("2025", loginUserInfor);
		response.setSuccess("修改货品：" + nums+ "+"+numst);

		return response;
	}
	
	private int updateProductIdentity(String yearInfo,UserInfor loginUserInfor) {
		int nums = 0;
		Year year = yearDaoImpl.getYearByName(yearInfo);
		//分组集合
		List<ProductDTO> products = new ArrayList<ProductDTO>();
		products = productDaoImpl.selectProducts(year);

		for (ProductDTO product : products) {
			//具体年份，季度，产品线，货品类别集合
			loggerLocal.error(product.toString());
			List<Product> pList = productDaoImpl.selectProducts(product);
			if (pList != null && pList.size() !=0) {
				for (int i=0;i<pList.size();i++) {
					Product pt = pList.get(i);				
					if (pt.getProductIdentity().equals("")) {
						String identiry = pt.getYear().getYear_Code() + pt.getQuarter().getQuarter_Code()+pt.getCategoryLevel1().getCategory_Code()+pt.getCategory().getCategory_Code();
						pt.setProductIdentity(identiry + Common_util.formatCode(i+1, 3));
						pt.setLastUpdateBy(loginUserInfor.getUser_name());
						pt.setLastUpdateTime(DateUtils.getNowDate());
						productDaoImpl.update(pt, true);
						nums++;
					}
					if (i == pList.size()-1) {
						ProductIdentitySequence ps = new ProductIdentitySequence();
						ps.setYearId(pt.getYear().getYear_ID());
						ps.setQuarterId(pt.getQuarter().getQuarter_ID());
						ps.setCategoryLevel1Id(pt.getCategoryLevel1().getCategory_ID());
						ps.setCateogryId(pt.getCategory().getCategory_ID());
						ps.setSequence(pList.size());
						productIsDaoImpl.save(ps, true);
					}
				}
			}	
		}
		return nums;
	}

	public Response updateProductUnit(ProductUnit productUnit) {
		Response response = new Response();
		
		int id = productUnit.getId();
		String unit = productUnit.getProductUnit();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(ProductUnit.class);
		criteria.add(Restrictions.eq("productUnit", unit));
		List<ProductUnit> units = productUnitDaoImpl.getByCritera(criteria, true);
		
		if (units == null || units.size() == 0){
			productUnitDaoImpl.saveOrUpdate(productUnit, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			ProductUnit unit2 = units.get(0);
			if (id != unit2.getId()){
				response.setQuickValue(Response.FAIL, "货品单位 重复,请检查重新输入");
			} else {
				productUnitDaoImpl.saveOrUpdate(productUnit, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}

	public Response updateNumPerHand(NumPerHand numPerHand) {
		Response response = new Response();
		
		int id = numPerHand.getId();
		int num = numPerHand.getNumPerHand();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(NumPerHand.class);
		criteria.add(Restrictions.eq("numPerHand", num));
		List<NumPerHand> numPerHands = numPerHandDaoImpl.getByCritera(criteria, true);
		
		if (numPerHands == null || numPerHands.size() == 0){
			numPerHandDaoImpl.saveOrUpdate(numPerHand, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			NumPerHand num2 = numPerHands.get(0);
			if (id != num2.getId()){
				response.setQuickValue(Response.FAIL, "齐码数量 重复,请检查重新输入");
			} else {
				numPerHandDaoImpl.saveOrUpdate(numPerHand, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}

	public Response updateColor(Color color) {
		Response response = new Response();
		
		int id = color.getColorId();
		String colorName = color.getName();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Color.class);
		criteria.add(Restrictions.eq("colorName", colorName));
		List<Color> colors = colorDaoImpl.getByCritera(criteria, true);
		
		if (colors == null || colors.size() == 0){
			String code = Common_util.getPinyinCode(color.getName(), true);
			color.setCode(code);
			colorDaoImpl.saveOrUpdate(color, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			Color colorName2 = colors.get(0);
			if (id != colorName2.getColorId()){
				response.setQuickValue(Response.FAIL, "相同颜色 重复,请检查重新输入");
			} else {
				String code = Common_util.getPinyinCode(color.getName(), true);
				color.setCode(code);
				colorDaoImpl.saveOrUpdate(color, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}
 
	
	/**
	 * to synchnize the color information from the jinsuan
	 * @return
	 */
	public Response synchnizeColor() {
		Response response = new Response();
		List<Color> colorsMS = colorMSDAOImpl.getAll(true);
		
		colorDaoImpl.deleteAll();
		
		for (Color color : colorsMS){
			String colorName = color.getName();
			if (colorName.indexOf("/") == -1){
			   String colorNamePinyin = Common_util.getPinyinCode(colorName, true);
			   color.setCode(colorNamePinyin);
		       colorDaoImpl.save(color, true);
			}
		}
		
		response.setReturnCode(Response.SUCCESS);
		return response;
	}
	
	/**
	 * to synchnize the size information from the jinsuan
	 * @return
	 */
	public Response synchnizeSize() {
		Response response = new Response();
		List<Size> sizesMS = sizeMSDAOImpl.getAll(true);
		
		sizeDaoImpl.deleteAll();
		
		for (Size size : sizesMS){
			String sizeName = size.getName();
			String sizeNamePinyin = Common_util.getPinyinCode(sizeName, true);
			size.setCode(sizeNamePinyin);
		    sizeDaoImpl.save(size, true);
		}
		
		response.setReturnCode(Response.SUCCESS);
		return response;
	}

	public Response updateInventory(HeadQInventoryStore store) {
		Response response = new Response();
		
		int id = store.getId();
		String unit = store.getName();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(HeadQInventoryStore.class);
		criteria.add(Restrictions.eq("name", unit));
		List<HeadQInventoryStore> units = inventoryStoreDAOImpl.getByCritera(criteria, true);
		
		if (units == null || units.size() == 0){
			store.setStatus(BaseOrder.STATUS_INITIAL);  // 添加仓库时，默认状态为0
			inventoryStoreDAOImpl.saveOrUpdate(store, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			HeadQInventoryStore unit2 = units.get(0);
			if (id != unit2.getId()){
				response.setQuickValue(Response.FAIL, "仓库已存在,请检查重新输入");
			} else {
				inventoryStoreDAOImpl.saveOrUpdate(store, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}

	public Response updateRole(ChainRoleType role) {
		Response response = new Response();
		
		int id = role.getChainRoleTypeId();
		String roleName = role.getChainRoleTypeName();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(ChainRoleType.class);
		criteria.add(Restrictions.eq("chainRoleTypeName", roleName));
		List<ChainRoleType> units = chainRoleTypeDaoImpl.getByCritera(criteria, true);
		
		if (units == null || units.size() == 0){
			role.setStatus(BaseOrder.STATUS_INITIAL);  // 添加角色时，默认状态为0
			chainRoleTypeDaoImpl.saveOrUpdate(role, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			ChainRoleType unit2 = units.get(0);
			if (id != unit2.getChainRoleTypeId()){
				response.setQuickValue(Response.FAIL, "系统角色已存在,请检查重新输入");
			} else {
				chainRoleTypeDaoImpl.saveOrUpdate(role, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}

	public Response updateHeadqTag(HeadQTag headQTag) {
		Response response = new Response();
		
		int id = headQTag.getId();
		String unit = headQTag.getTagName();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(HeadQTag.class);
		criteria.add(Restrictions.eq("tagName", unit));
		List<HeadQTag> units = headQTagDaoImpl.getByCritera(criteria, true);
		
		if (units == null || units.size() == 0){
			
			headQTagDaoImpl.saveOrUpdate(headQTag, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			HeadQTag unit2 = units.get(0);
			if (id != unit2.getId()){
				response.setQuickValue(Response.FAIL, "标签已存在,请检查重新输入");
			} else {
				headQTagDaoImpl.saveOrUpdate(headQTag, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}
	
	
	/**
	 * 新增或者修改标签组
	 * @param headQTagGroup
	 * @return
	 */
	public Response updateHeadqTagGroup(HeadQTagGroup headQTagGroup) {
		Response response = new Response();
		
		int id = headQTagGroup.getId();
		String unit = headQTagGroup.getGroupName();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(HeadQTagGroup.class);
		criteria.add(Restrictions.eq("groupName", unit));
		List<HeadQTagGroup> units = headQTagGroupDaoImpl.getByCritera(criteria, true);
		
		if (units == null || units.size() == 0){
			
			headQTagGroupDaoImpl.saveOrUpdate(headQTagGroup, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			HeadQTagGroup unit2 = units.get(0);
			if (id != unit2.getId()){
				response.setQuickValue(Response.FAIL, "标签已存在,请检查重新输入");
			} else {
				headQTagGroupDaoImpl.saveOrUpdate(headQTagGroup, true);
				response.setReturnCode(Response.SUCCESS);
			}
		}
		
		return response;
	}

	public BasicDataActionUIBean setTagGroups() {
		BasicDataActionUIBean  uiBean = new BasicDataActionUIBean();
		List<HeadQTagGroup> groups = headQTagGroupDaoImpl.getAll(true);
		uiBean.setTagGroups(groups);
		return uiBean;		
	}

	public Response updateExpenseHqType(ExpenseHqType expenseHqType,UserInfor loginUserInfor) {
		Response response = new Response();
		if (expenseHqType.getParentId() == ExpenseHqType.PARENT_CHAIN || expenseHqType.getParentId() == ExpenseHqType.PARENT_HQ) {
			expenseHqType.setParentId(null);
		}
		
		ExpenseHqType et = expenseHqTypeImpl.get(expenseHqType.getId(), true);	
		expenseHqType.setDelflag(0);
		if (et == null){		
			expenseHqType.setCreateBy(loginUserInfor.getUser_name());
			expenseHqType.setCreateTime(Common_util.getToday());
			expenseHqTypeImpl.saveOrUpdate(expenseHqType, true);
			response.setReturnCode(Response.SUCCESS);
		} else {
			expenseHqType.setUpdateBy(loginUserInfor.getUser_name());
			expenseHqType.setUpdateTime(Common_util.getToday());
			expenseHqTypeImpl.saveOrUpdate(expenseHqType, true);
			response.setReturnCode(Response.SUCCESS);			
		}
		
		return response;
	}

	public Response selectSystemConfig(BasicDataActionFormBean formBean, int page, int rows, String sort,
			String order) {
		Response response = new Response();
		Map dataMap = new HashMap();
		List<SystemConfigVO> vos = new ArrayList<SystemConfigVO>();
		
		//获取总条数的 criteria
		DetachedCriteria sysTemTotalCriteria = DetachedCriteria.forClass(SystemConfig.class);
		//获取list的 criteria
		DetachedCriteria sCriteria = DetachedCriteria.forClass(SystemConfig.class);
		
		sCriteria.add(Restrictions.eq("delflag", SystemConfig.IS_NORMAL));
		
		//1. 获取总条数
		sysTemTotalCriteria.setProjection(Projections.rowCount());
		int total = Common_util.getProjectionSingleValue(systemConfigDaoImpl.getByCriteriaProjection(sysTemTotalCriteria, true));		

		List<SystemConfig> sys = systemConfigDaoImpl.getByCritera(sCriteria, Common_util.getFirstRecord(page, rows), rows, true);
		if (sys.size() != 0) {
			for (SystemConfig systemConfig : sys) {
				SystemConfigVO vo = new SystemConfigVO();
				vo.setId(systemConfig.getId());
				vo.setConfigName(systemConfig.getConfigName());
				vo.setValue(systemConfig.getValue());
				vo.setConfigCode(systemConfig.getConfigCode());
				vo.setSort(systemConfig.getSort());
				vo.setType(systemConfig.getType());
				if (systemConfig.getType() == 0) {
					vo.setTypeS("总部配置");
				}else if (systemConfig.getType() == 1) {
					vo.setTypeS("店铺配置");
				}else if (systemConfig.getType() == 2) {
					vo.setTypeS("服务器配置");
				}else if (systemConfig.getType() == 3) {
					vo.setTypeS("品牌配置");
				}
				vo.setStatus(systemConfig.getStatus());
				if (systemConfig.getStatus() == 0) {
					vo.setStatusS("正常");
				}else {
					vo.setStatusS("停用");
				}
				vo.setCreateBy(systemConfig.getCreateBy());
				vo.setCreateTime(Common_util.dateFormat_f.format(systemConfig.getCreateTime()));
				vo.setUpdateBy(systemConfig.getUpdateBy());
				if (systemConfig.getUpdateTime() != null) {
					vo.setUpdateTime(Common_util.dateFormat_f.format(systemConfig.getUpdateTime()));
				}				
				vo.setComment(systemConfig.getComment());
				vos.add(vo);
			}
		}
		
		dataMap.put("rows", vos);
		dataMap.put("total", total);

		response.setReturnValue(dataMap);
		response.setReturnCode(Response.SUCCESS);
		return response;
	}
	
	public Response selectSystemFiles() {
		Response response = new Response();
		Map dataMap = new HashMap();
		List<SystemFile> files = systemFileDaoImpl.getAll(true);
		for (SystemFile systemFile : files) {
			systemFile.setCreateTimes(Common_util.dateFormat_f.format(systemFile.getCreateTime()));
			if (systemFile.getUpdateTime() != null) {
				systemFile.setUpdateTimes(Common_util.dateFormat_f.format(systemFile.getUpdateTime()));
			}
		}

		dataMap.put("rows", files);
		response.setReturnValue(dataMap);
		response.setReturnCode(Response.SUCCESS);
		return response;
	}

	
	/**
	 * 获取菜单信息
	 * @param formBean
	 * @return
	 */
	public Response selectMenus() {
		Response response = new Response();
		//获取菜单目录
		List<Menu> list = menuService.getMenusByLevel(Menu.MENY_TYPE_MENU);
		if (list.size() !=0) {
			for (Menu m : list) {				
				m.setCreateTimes(Common_util.dateFormat_f.format(m.getCreateTime()));
				m.init();
				//查询目录菜单
				List<Menu> mts = menuService.getMenusByParentId(m.getId());
				if (mts.size() != 0) {
					for (Menu menu : mts) {
						//查询目录按钮
						List<Menu> buttons = menuService.getMenusByParentId(menu.getId());
						if (buttons.size() !=0) {
							for (Menu bs : buttons) {
								bs.setCreateTimes(Common_util.dateFormat_f.format(bs.getCreateTime()));
								bs.init();
							}
							menu.setChildren(buttons);
						}
						menu.setCreateTimes(Common_util.dateFormat_f.format(m.getCreateTime()));
						menu.init();
					}
					m.setChildren(mts);
					
				}
				
			}
		}

		response.setReturnValue(list);
		return response;
	}
	
	@Autowired
	MenuDaoImpl menuDaoImpl;

	
	
	/**
	 * 新增/修改菜单
	 * @param menu
	 * @param loginUserInfor
	 * @return
	 */
	public Response updateSystemMenu(Menu menu, UserInfor loginUserInfor) {
		Response response = new Response();
		
		Menu mu = menuDaoImpl.get(menu.getId(), true);	

		if (mu == null){	
			//插入新菜单时候：需要菜单路径查询
			if (StringUtils.isNotBlank(menu.getMenuPath())) {
				Boolean isExist = menuDaoImpl.selectMenuByPath(menu.getMenuPath());
				if (isExist) {
					response.setFail(menu.getMenuPath()+":路径已存在,请重新输入菜单路径");
				}else {
					menu.setCreateBy(loginUserInfor.getUser_name());
					menu.setCreateTime(Common_util.getToday());
					menuDaoImpl.saveOrUpdate(menu, true);
					response.setReturnCode(Response.SUCCESS);
				}	
			}	
		} else {
			mu.setMenuName(menu.getMenuName());
			mu.setMenuPath(menu.getMenuPath());
			mu.setMenuType(menu.getMenuType());
			mu.setMenuDescribe(menu.getMenuDescribe());
			mu.setMenuSign(menu.getMenuSign());
			mu.setStatus(menu.getStatus());
			mu.setIsHidden(menu.getIsHidden());
			mu.setSort(menu.getSort());
			mu.setParentId(menu.getParentId());
			mu.setUpdateBy(loginUserInfor.getUser_name());
			mu.setUpdateTime(Common_util.getToday());
			menuDaoImpl.saveOrUpdate(mu, true);
			response.setReturnCode(Response.SUCCESS);			
		}
		
		return response;
	}

	
	/**
	 * 根据角色ID查询角色拥有的权限树
	 * @param roleId
	 * @return
	 */
	public Response selectFunctionTree(int roleId) {
		Response response = new Response();
		

		//获取菜单目录
		List<Menu> list = menuService.getMenusByLevel(Menu.MENY_TYPE_MENU);

		List<MenuVO> mVos = new ArrayList<MenuVO>();//菜单
						
		if (list.size() !=0) {
			for (Menu m : list) {				
							
				//查询目录菜单
				List<Menu> mts = menuService.getMenusByParentId(m.getId());	
				List<MenuVO> cVos = new ArrayList<MenuVO>();//目录
				if (mts.size() != 0) {
					for (Menu c : mts) {	
						if(c.getIsHidden() == Menu.HIDDEN_FALSE) { //是否是隐藏菜单
						
						List<Menu> buttons = menuService.getMenusByParentId(c.getId());	//查询目录按钮
						List<MenuVO> bVos = new ArrayList<MenuVO>();//按钮
						boolean ccIsCheck = true;
						if (buttons.size() !=0) {
							for (Menu b : buttons) {
								MenuVO bb = new MenuVO();
								bb.setId(b.getId());
								bb.setText(b.getMenuName() + " " + b.getId());

								// 判断角色是否拥有该按钮权限	
								SystemRoleMenu systemRoleMenu = systemRoleMenuDaoImpl.getSystemRoleMenu(roleId,b.getId());
								if (systemRoleMenu != null) {
									bb.setChecked(true);
								}else {
									ccIsCheck = false;
								}				
								bVos.add(bb);
							}							
						}
						
						MenuVO cc = new MenuVO();
						cc.setId(c.getId());
						// 判断角色是否拥有该目录权限	
						SystemRoleMenu systemRoleMenu = systemRoleMenuDaoImpl.getSystemRoleMenu(roleId,c.getId());
						if (systemRoleMenu != null && ccIsCheck) {
							cc.setChecked(true);
						}
						cc.setText(c.getMenuName() + " " + c.getId() );
						cc.setChildren(bVos);
						cVos.add(cc);
						}
					}
										
				}
				if(m.getIsHidden() == Menu.HIDDEN_FALSE) {
					MenuVO mm = new MenuVO();
					mm.setId(m.getId());
					mm.setText(m.getMenuName());	
					mm.setChildren(cVos);
					mm.setState("closed");
					mVos.add(mm);
				}
			}
		}
		
		
		response.setReturnValue(mVos);		
		return response;
	}
	

	/**
	 * 修改角色权限
	 * @param roleId
	 * @param menuIds
	 * @return
	 */
	public Response updateRoleFunctions(int roleId, String menuIds,UserInfor loginUserInfor) {
		Response response = new Response();

		ChainRoleType role = chainRoleTypeDaoImpl.get(roleId, true);
		if (role != null && role.getChainRoleTypeId()  == ChainRoleType.HEAD_ADMIN  && loginUserInfor.getRoleType() != ChainRoleType.HEAD_ADMIN) {
			response.setFail("系统管理员权限无法修改");
		}else if (role != null ) {
			systemRoleMenuDaoImpl.deleteRoleMenus(roleId);
			List<String> mIds = Arrays.asList(menuIds.split(","));
			if (mIds.size() !=0) {
				for (String id : mIds) {
					SystemRoleMenu roleMenu = new SystemRoleMenu();
					roleMenu.setRoleId(roleId);
					roleMenu.setMenuId(Integer.valueOf(id));
					systemRoleMenuDaoImpl.save(roleMenu, true);
				}
			}
			response.setSuccess("权限分配成功");
		}else {
			response.setFail("权限分配失败,未知角色信息");
		}
		
		return response;
	}

	
	/**
	 * 删除文件
	 * @param id
	 * @return
	 */
	public Response deledeFileById(int fileId,String urlPath,UserInfor user) {
		Response response = new Response();
		SystemFile systemFile = new SystemFile();
		if(!user.getFunctions().contains(urlPath)) {
			response.setFail("权限不足");
			return response;
		}
		if (fileId != Common_util.ALL_RECORD_NEW) {
			systemFile = systemFileDaoImpl.get(fileId, true);
			 if (systemFile != null) {
					String filePath = SystemParm.getParm("QX_SYSTEM_FILE") + "/" + systemFile.getFileName();
					File file = new File(filePath);
					if (file.exists()) {
						file.delete();
						systemFileDaoImpl.delete(systemFile, true);
						response.setSuccess(systemFile.getFileName()+"删除成功");
					}else {
						response.setFail("文件不存在");
					}
			}
		}else {
			response.setFail("删除异常");
		}
		
		return response;
	}


}
